import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import useUserStore from '@/store/modules/user'
const { VITE_BASE_URL } = import.meta.env

const request = axios.create({
    baseURL: VITE_BASE_URL,
    withCredentials: true,
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })

  request.interceptors.request.use(
    config => {
      const userStore = useUserStore()
      const token = userStore.authToken || sessionStorage.getItem('authToken')
      if (token && config.headers) {
        config.headers['Authorization'] = `${token}`
      }
      return config
    },
    error => {
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )

  // response interceptor
request.interceptors.response.use(
    response => {
      const res = response.data || {}
      if (res.code === 406) {
        // 登录超时
        toLogin()
      }
      return Promise.resolve(res)
    },
    error => {
      console.log('err' + error) // for debug
      switch (error?.response?.status) {
        case 401: {
          ElMessage.error('用户未登录')
          toLogin()
          break
        }
        case 403: {
           ElMessage.warning('权限不足')
           break
        }
        case 500: {
           ElMessage.error('服务异常，请稍后再试')
           break
        }
        default: {
          break
        }
      }
      return Promise.reject(error)
    }
  )
  

  const toLogin = () => {
    router.push('/login')
  }

  export default request